package com.basker.pisces.orm.database;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.basker.pisces.core.meta.IDataObjectMeta;
import com.basker.pisces.core.meta.annotation.DataObjectMeta;
import com.basker.pisces.core.meta.bean.BeanMetaManager;
import com.basker.pisces.core.meta.bean.BeanMetaTypeWrapperRegistrar.BeanMetaTypeWrapper;
import com.basker.pisces.orm.data.meta.DataSetMeta;
import com.basker.pisces.redis.sequence.RedisSequenceGenerator;

/**
 * 获取所有BeanMeta,将其映射的数据表当前最大整型主键值同步到redis序列对象
 *
 * @author hangwen
 */
public class BeanMetaRedisSequenceSynchronizer implements InitializingBean {

    @Autowired(required = false)
    private List<BeanMetaTypeWrapper> beanMetaTypeWrappers;

    @Autowired(required = false)
    private RedisSequenceGenerator redisSequenceGenerator;

    @Override
    public void afterPropertiesSet() throws Exception {
        trySynRedisSeq();
    }

    private void trySynRedisSeq() {
        if (redisSequenceGenerator == null || CollectionUtils.isEmpty(this.beanMetaTypeWrappers)) {
            return;
        }

        for (BeanMetaTypeWrapper dataObjectMetaTypeWrapper : beanMetaTypeWrappers) {
            Class<?> beanType = dataObjectMetaTypeWrapper.getBeanType();
            DataObjectMeta annotation = beanType.getAnnotation(DataObjectMeta.class);

            if (StringUtils.isEmpty(annotation.tableName())) {
                continue;
            }

            IDataObjectMeta objectMeta = BeanMetaManager.getBeanMeta(beanType);
            if (objectMeta.isReadOnly()) {
                continue;
            }

            DataSetMeta dataSetMeta = DataSetMeta.create(objectMeta);

            RedisSequenceSynchronizer tableLongIdValueRedisSynchronizer = new RedisSequenceSynchronizer(dataSetMeta,
                    redisSequenceGenerator);
            tableLongIdValueRedisSynchronizer.syn();
        }
    }

}
